import { useEffect, useMemo, useRef } from 'react';

import api from '@/api';
import Image from '@/components/Image';
import req from '@/utils/req';
import useSetState from '@/utils/useSetState';

import LoginModal from '../LoginModal';
import classes from './index.module.less';

type Props = {
  type?: 'my' | 'all';
  dataModule?: string;
};
type ImageItemType = {
  height: number;
  id: number;
  prompt: string;
  sort: number;
  thumbnail_url: string;
  thumbnail: string;
  title: string;
  url: string;
  image_url: string;
  left: number;
  top: number;
  width: number;
};
const gap = 10;
const FlowImage: React.FC<Props> = ({ type = 'all' }) => {
  const refLoading = useRef(false);
  const [{ page, page_size, list, hasMore, height }, setState] = useSetState({
    page: 1,
    page_size: 10,
    list: [] as ImageItemType[],
    openText: '',
    open: false,
    height: 0,
    hasMore: true,
  });
  const { width } = useMemo(() => {
    const windowWidth = innerWidth;
    const width = (windowWidth - 24 - gap) / 2;

    return { width };
  }, []);

  function load(isMore = false) {
    if (refLoading.current) {
      return;
    }
    refLoading.current = true;

    if (type === 'all') {
      req
        .get<ImageItemType[]>(api.getArtRandList)
        .then((items) => {
          newFunction(page, items, items.length, items.length);
        })
        .finally(() => {
          refLoading.current = false;
        });
    }
    if (type === 'my') {
      req
        .post<{
          page: number;
          page_size: number;
          items: ImageItemType[];
          total: number;
        }>(api.artUserArtList, {
          page: isMore ? page + 1 : 1,
          page_size,
        })
        .then(({ items, page, page_size, total }) => {
          newFunction(page, items, page_size, total);
        })
        .finally(() => {
          refLoading.current = false;
        });
    }

    function newFunction(page: number, items: ImageItemType[], page_size: number, total: number) {
      const H = [0, 0];
      if (page > 1) {
        items = list.concat(items);
      }
      items = items.map((img) => {
        const tag = H.indexOf(Math.min(...H));
        img.height = img.height ? img.height * 1 : 1000;
        img.width = img.width ? img.width * 1 : 1000;
        const left = tag * (width + gap);
        const top = H[tag];
        H[tag] += (img.height * width) / img.width + gap;
        return {
          ...img,
          width,
          height: (img.height * width) / img.width,
          left,
          top,
        };
      });

      const height = Math.max(...H);

      setState({
        list: items,
        page,
        page_size,
        height,
        hasMore: total > page * page_size,
      });
      return items;
    }
  }

  useEffect(() => {
    load();
  }, []);

  return (
    <div
      className={classes.wrap}
      style={{ paddingTop: 10 }}
      // onScrollToLower={() => {
      //   if (hasMore) {
      //     load(true);
      //   }
      // }}
      // scroll-y
    >
      <div className={classes.box} style={{ height }}>
        {list.map((t) => (
          <div
            className={classes.imageBox}
            key={t.id}
            style={{
              width: t.width,
              height: t.height,
              left: t.left + 12,
              top: t.top,
            }}
          >
            <Image
              loadLazy
              style={{ width: t.width, height: t.height }}
              mode="aspectFill"
              src={t.thumbnail || t.thumbnail_url}
            />
            <LoginModal>
              <div
                className={classes.text}
                onClick={() => {
                  // Taro.showActionSheet({
                  //   itemList: ['复制提示词', '下载作品'],
                  //   fail() {},
                  //   success(msg) {
                  //     if (msg.tapIndex == 0) {
                  //       Taro.setClipboardData({ data: t.prompt });
                  //       buryPoint(dataModule, '复制提示词');
                  //     }
                  //     if (msg.tapIndex == 1) {
                  //       const url = t.image_url || t.url;
                  //       loadImage(url);
                  //       buryPoint(dataModule, '下载作品');
                  //     }
                  //   },
                  // });
                }}
              >
                {t.prompt}
              </div>
            </LoginModal>
          </div>
        ))}
      </div>
    </div>
  );
};

export default FlowImage;
